package com.neuedu.mp.framework;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.neuedu.mp.entity.SysUser;
import com.neuedu.mp.utils.JWTUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class TokenFilter implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        System.out.println("request.getRequestURI() = " + request.getRequestURI());

        String token = request.getHeader("Authorization");
        if(ObjectUtils.isNotEmpty(token)){
            SysUser sysUser = JWTUtils.decode(token);
            request.setAttribute("user",sysUser);
            if(sysUser != null){
                return true;
            }

        }



        //认证失败  401
        ObjectMapper objectMapper = new ObjectMapper();
        Ret ret = Ret.unauthorized("");
        String json = objectMapper.writeValueAsString(ret);


        response.setContentType("application/json;charaset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(json);

        writer.close();
        writer.flush();


        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
